import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';

class StationStatusView extends StatefulWidget {
  const StationStatusView({super.key, this.id, this.status});
  final int? id;
  final Map<String, dynamic>? status;
  @override
  State<StationStatusView> createState() => _StationStatusViewState();

  static show(
    context, {
    int? id,
    Map<String, dynamic>? status,
  }) {
    showModalBottomSheet(
      context: context,
      showDragHandle: true,
      backgroundColor: UiTheme(context).bottomSheetBackgroundColor,
      isScrollControlled: true,
      constraints:
          BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.85),
      builder: (context) {
        return StationStatusView(
          id: id,
          status: status,
        );
      },
    );
  }
}

class _StationStatusViewState extends State<StationStatusView> {
  Map<String, dynamic> status = {};
  bool loading = false;
  @override
  void initState() {
    if (widget.status != null && widget.status?['station_id'] != null) {
      setState(() {
        status = widget.status!;
      });
    } else {
      fetchStatus();
    }

    super.initState();
  }

  fetchStatus() async {
    setState(() {
      loading = true;
    });
    await 0.2.delay();
    var res = await Http.instance.post('/api/information/station/status',
        data: {'station_id': widget.id});
    if (res.code == 1) {
      setState(() {
        loading = false;
        status = res.data;
      });
    } else {
      Ui.toast(res.msg);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: SizedBox(
        width: double.infinity,
        child: loading
            ? const Center(
                child: CupertinoActivityIndicator(),
              )
            : Column(
                children: [
                  UiTap(
                    onTap: () {
                      App.push(
                          '/basic/station/detail?id=${status['station_id']}');
                    },
                    child: SizedBox(
                      child: Text(
                        status['station_name'] ?? '',
                        style: const TextStyle(fontSize: 18),
                      ),
                    ),
                  ),
                  UiTap(
                    onTap: () {
                      App.push(
                          '/basic/company/detail?id=${status['company_id']}');
                    },
                    child: Opacity(
                      opacity: 0.6,
                      child: Text(
                        '${status['company_name'] ?? ''}',
                      ),
                    ),
                  ),
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.only(
                        top: UiTheme.spacingX,
                        left: UiTheme.spacingX,
                        right: UiTheme.spacingX,
                        bottom: 25,
                      ),
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(UiTheme.boxRadiusX),
                        child: status['station_params']?.length == 0
                            ? const UiResult(
                                ikon: 'offline',
                                text: '该设备已离线',
                              )
                            : SingleChildScrollView(
                                child: Column(
                                  children: List.generate(
                                      status['station_params']?.length ?? 0,
                                      (index) {
                                    var item = status['station_params'][index];
                                    return Container(
                                      margin: const EdgeInsets.only(
                                          bottom: UiTheme.spacingX),
                                      padding:
                                          const EdgeInsets.all(UiTheme.spacing),
                                      decoration: BoxDecoration(
                                          color:
                                              UiTheme(context).panelBackground,
                                          border: Border.all(
                                              width: 0.2,
                                              color: Colors.black
                                                  .withOpacity(0.2)),
                                          borderRadius: BorderRadius.circular(
                                              UiTheme.boxRadiusX)),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Container(
                                            padding: const EdgeInsets.symmetric(
                                                horizontal: UiTheme.spacing,
                                                vertical: 8),
                                            decoration: BoxDecoration(
                                                color: UiTheme(context)
                                                    .panelBackground,
                                                border: Border.all(
                                                    width: 0.2,
                                                    color: Colors.black
                                                        .withOpacity(0.2)),
                                                borderRadius:
                                                    BorderRadius.circular(
                                                        UiTheme.boxRadiusX)),
                                            child: Row(
                                              children: [
                                                if (item['second_net'] != '')
                                                  Container(
                                                    width: 5,
                                                    height: 15,
                                                    decoration: BoxDecoration(
                                                      color: UiTheme.of(context)
                                                          .primaryColor,
                                                      borderRadius:
                                                          BorderRadius.circular(
                                                              5),
                                                    ),
                                                  ),
                                                if (item['second_net'] != '')
                                                  const SizedBox(width: 5),
                                                Text(
                                                  item['second_net'],
                                                  style: const TextStyle(
                                                    fontSize: 16,
                                                    fontWeight: FontWeight.bold,
                                                  ),
                                                ),
                                                if (item['second_net'] != '')
                                                  Expanded(
                                                    child: Container(),
                                                  ),
                                                const Text('运行状态：'),
                                                Text(
                                                  status['status_name'],
                                                  style: status['status'] ==
                                                          null
                                                      ? null
                                                      : TextStyle(
                                                          color:
                                                              status['status'] ==
                                                                      'online'
                                                                  ? const Color
                                                                      .fromARGB(
                                                                      255,
                                                                      51,
                                                                      179,
                                                                      55)
                                                                  : Colors
                                                                      .redAccent,
                                                          fontWeight:
                                                              FontWeight.w500,
                                                        ),
                                                ),
                                              ],
                                            ),
                                          ),
                                          const SizedBox(height: 10),
                                          Column(
                                            children: List.generate(
                                              item['params'].length,
                                              (index) => Padding(
                                                padding:
                                                    const EdgeInsets.symmetric(
                                                        vertical: 3),
                                                child: Row(
                                                  children: [
                                                    Text(
                                                      '${item['params'][index]['param_name']}：',
                                                    ),
                                                    Text(
                                                      '${item['params'][index]['param_value']}${item['params'][index]['param_unit'] ?? ''}',
                                                      style: const TextStyle(
                                                        fontWeight:
                                                            FontWeight.w500,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            ),
                                          ),
                                          Row(
                                            children: [
                                              const Text('最后更新：'),
                                              Text(
                                                '${item['update_time_format'] ?? '--'}',
                                                style: const TextStyle(
                                                  fontWeight: FontWeight.w500,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    );
                                  }),
                                ),
                              ),
                      ),
                    ),
                  ),
                ],
              ),
      ),
    );
  }
}
